import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
const _axios = axios.create({
  baseURL: process.env.VUE_APP_BASE_API
})
// 请求拦截
_axios.interceptors.request.use(
  (config) => {
    if (store.state.user.token) {
      config.headers.Authorization = `Bearer ${store.state.user.token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)
// 响应拦截
_axios.interceptors.response.use(
  (res) => {
    // 统一错误处理
    if (res.data.success) {
      return res.data
    } else {
      // 失败：提示一下
      Message.error(res.data.message)
      // 直接让后面api调用执行.catch中止.then执行
      return Promise.reject(res.data.message)
    }
  },
  (error) => {
    if (error.response.status === 401) {
      store.commit('user/logout')
      router.push('/login?redirect=' + location.href.split('#')[1])
    }
    return Promise.reject(error)
  }
)
export default _axios
